"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 防篡改
Case Name   : 普通用户、安全管理员在私有schema下创建的function需要移除public对函数的执行权和用户的执行权
Create At   : 2022/3/25
Owner       : opentestcase012
Description :
    1.设置参数并重启数据库enableseparationofduty=on
    2.创建普通用户和createrole用户
    3.普通用户连接，创建函数1
    4.安全管理员连接，创建函数2
    5.移除public函数2的执行权，移除普通用户对函数1的执行权
    6.普通用户连接，调用函数1
    7.安全管理员连接，调用函数2
    8.移除public函数1的执行权，移除安全管理员对函数2的执行权
    9.普通用户连接，调用函数1
    10.安全管理员连接，调用函数2
    11.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.成功
    6.成功
    7.成功
    8.成功
    9.失败
    10.失败
    11.清理环境成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import macro


class Security(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.u_name = 'u_security_function_privilege_0011_01'
        self.u_name_01 = 'u_security_function_privilege_0011_02'
        self.f_name = 'f_security_delete_privilege_0011'
        self.default_value1 = self.common.show_param('enableSeparationOfDuty')

    def test_security(self):
        text = '-----step1：设置参数并重启数据库enableSeparationOfDuty=on; ' \
               'expect:成功-----'
        self.log.info(text)
        mod_msg = self.pri_sh.execute_gsguc('set',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            'enableSeparationOfDuty=on')
        self.assertTrue(mod_msg, '执行失败:' + text)
        result = self.pri_sh.restart_db_cluster()
        self.assertTrue(result, '执行失败' + text)

        text = '-----step2：创建普通用户和createrole用户 expect:成功-----'
        self.log.info(text)
        create_cmd = f"drop user if exists {self.u_name}" \
            f",{self.u_name_01} cascade; " \
            f"create user {self.u_name} password  '{macro.COMMON_PASSWD}';" \
            f"create user {self.u_name_01} createrole " \
            f"password  '{macro.COMMON_PASSWD}';"
        msg = self.pri_sh.execut_db_sql(create_cmd)
        self.log.info(msg)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, msg,
                      '执行失败:' + text)
        self.assertEqual(2, msg.count(self.constant.CREATE_ROLE_SUCCESS_MSG),
                         '执行失败:' + text)

        text = '-----step3：普通用户连接，创建函数1; expect:成功-----'
        self.log.info(text)
        sql_cmd = f"drop function if exists {self.u_name}.{self.f_name};" \
            f"create function {self.u_name}.{self.f_name}() " \
            f"return varchar as " \
            f"begin return 'gaussdb is better than oracle';end;"
        connect_noruser = f'-U {self.u_name} -W {macro.COMMON_PASSWD}'
        msg = self.pri_sh.execut_db_sql(sql_cmd, sql_type=connect_noruser)
        self.log.info(msg)
        self.assertIn(self.constant.DROP_FUNCTION_SUCCESS_MSG, msg,
                      '执行失败:' + text)
        self.assertIn(self.constant.CREATE_FUNCTION_SUCCESS_MSG, msg,
                      '执行失败:' + text)

        text = '-----step4：安全管理员连接，创建函数2; expect:成功-----'
        self.log.info(text)
        sql_cmd = f"drop function if exists {self.u_name_01}.{self.f_name};" \
            f"create function {self.u_name_01}.{self.f_name}() " \
            f"return varchar as " \
            f"begin return 'gaussdb is better than oracle';end;"
        connect_createrole = f'-U {self.u_name_01} -W {macro.COMMON_PASSWD}'
        msg = self.pri_sh.execut_db_sql(sql_cmd, sql_type=connect_createrole)
        self.log.info(msg)
        self.assertIn(self.constant.DROP_FUNCTION_SUCCESS_MSG, msg,
                      '执行失败:' + text)
        self.assertIn(self.constant.CREATE_FUNCTION_SUCCESS_MSG, msg,
                      '执行失败:' + text)

        text = '-----step5：移除public函数2的执行权，移除普通用户对函数1的执行权 expect:成功-----'
        self.log.info(text)
        create_cmd = f"revoke execute on function " \
            f"{self.u_name_01}.{self.f_name}() from public;" \
            f"revoke execute on function {self.u_name}.{self.f_name}() " \
            f"from {self.u_name};"
        msg = self.pri_sh.execut_db_sql(create_cmd)
        self.log.info(msg)
        self.assertEqual(2, msg.count(self.constant.REVOKE_SUCCESS_MSG),
                         '执行失败:' + text)

        text = '-----step6：普通用户连接，调用函数1 expect:成功-----'
        self.log.info(text)
        call_cmd = f"call {self.u_name}.{self.f_name}();"
        msg = self.pri_sh.execut_db_sql(call_cmd, sql_type=connect_noruser)
        self.log.info(msg)
        self.assertIn('gaussdb is better than oracle', msg, '执行失败:' + text)

        text = '-----step7：安全管理员连接，调用函数2 expect:成功-----'
        self.log.info(text)
        call_cmd = f"call {self.u_name_01}.{self.f_name}();"
        msg = self.pri_sh.execut_db_sql(call_cmd, sql_type=connect_createrole)
        self.log.info(msg)
        self.assertIn('gaussdb is better than oracle', msg, '执行失败:' + text)

        text = '-----step8：移除public函数1的执行权，移除安全管理员对函数2的执行权 expect:成功-----'
        self.log.info(text)
        create_cmd = f"revoke execute on function " \
            f"{self.u_name}.{self.f_name}() from public;" \
            f"revoke execute on function {self.u_name_01}.{self.f_name}() " \
            f"from {self.u_name_01};"
        msg = self.pri_sh.execut_db_sql(create_cmd)
        self.log.info(msg)
        self.assertEqual(2, msg.count(self.constant.REVOKE_SUCCESS_MSG),
                         '执行失败:' + text)

        text = '-----step9：普通用户连接，调用函数1 expect:失败-----'
        self.log.info(text)
        call_cmd = f"call {self.u_name}.{self.f_name}();"
        msg = self.pri_sh.execut_db_sql(call_cmd, sql_type=connect_noruser)
        self.log.info(msg)
        self.assertIn('permission denied', msg, '执行失败:' + text)

        text = '-----step10：安全管理员连接，调用函数2 expect:失败-----'
        self.log.info(text)
        call_cmd = f"call {self.u_name_01}.{self.f_name}();"
        msg = self.pri_sh.execut_db_sql(call_cmd, sql_type=connect_createrole)
        self.log.info(msg)
        self.assertIn('permission denied', msg, '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----step11：清理环境-----')
        text1 = '-----删除用户 expect:成功-----'
        self.log.info(text1)
        drop_cmd = f"drop user if exists {self.u_name}," \
            f"{self.u_name_01} cascade;"
        drop_msg = self.pri_sh.execut_db_sql(drop_cmd)
        self.log.info(drop_msg)

        text2 = '-----修改参数enableSeparationOfDuty为初始值 expect:成功-----'
        self.log.info(text2)
        mod_msg1 = self.pri_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'enableSeparationOfDuty='
                                             f'{self.default_value1}')
        restart_res = self.pri_sh.restart_db_cluster()

        self.log.info('-----断言tearDown执行成功-----')
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, drop_msg,
                      '执行失败:' + text1)
        self.assertTrue(mod_msg1, '执行失败:' + text2)
        self.assertTrue(restart_res, '执行失败:' + text2)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
